//
//  OrderViewController.m
//  MagazineShangejie
//
//  Created by mac on 15/3/18.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//

#import "OrderViewController.h"
#import <DPMeterView.h>
#import "UIBezierPath+BasicShapes.h"
#import "Util.h"
#import "LoginViewController.h"
#import <StoreKit/StoreKit.h>

@interface OrderViewController ()<UIAlertViewDelegate,SKProductsRequestDelegate,SKPaymentTransactionObserver>{
    NSMutableArray*itmeButtons;
    UIImageView*jiantou;
    SKProduct *t_product;
    NSString*magid;
    NSString*magidKey;
    
    
    
    __weak IBOutlet UIView *litleBlackView;
    __weak IBOutlet UIView *newOrderBackGround;
    
}

@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"订阅";
//    [UserDefaults setObject:@"right" forKey:@"center"];
    
    
    [self initItmes];
    [self initData];
    
    
    UIButton *buttonf=[UIButton buttonWithType:UIButtonTypeCustom];
    [buttonf setFrame:CGRectMake(0, 0, 22, 22)];
    [buttonf addTarget:self action:@selector(popOfDismss) forControlEvents:UIControlEventTouchUpInside];
    [buttonf setImage:[UIImage imageNamed:@"dismiss"] forState:UIControlStateNormal];
    
    NSString *newOldYear = [UserDefaults objectForKey:@"NewYear" ];
    if ([newOldYear isEqualToString:@"NewYear"]) {
        //状态栏的文字颜色换成白色
        //        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        
            //            [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
            [buttonf setImage:[UIImage imageNamed:@"dismissGray"] forState:UIControlStateNormal];
        
    }
 
    UIBarButtonItem*leftBarItem = [[UIBarButtonItem alloc]initWithCustomView:buttonf];
    self.navigationItem.leftBarButtonItem=leftBarItem;
    
    // Do any additional setup after loading the view.
    
    
    [self.view bringSubviewToFront:newOrderBackGround];
    
    newOrderBackGround.hidden = YES;
    litleBlackView.hidden = YES;
    
    ////添加返回手势
    UITapGestureRecognizer *hiddenRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenBlackBG)];
//    [hiddenRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    hiddenRecognizer.numberOfTapsRequired = 1; // 单击
    [litleBlackView addGestureRecognizer:hiddenRecognizer];
}

-(void)hiddenBlackBG{
    newOrderBackGround.hidden = YES;
    litleBlackView.hidden = YES;
}


-(void)popOfDismss{
    
    //        [self goBack];
    [self.navigationController popViewControllerAnimated:YES];
    
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)viewDidAppear:(BOOL)animated{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
- (void)viewDidDisappear:(BOOL)animated{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
-(void)initData{
    UIImageView*image=(UIImageView*)[self.view viewWithTag:11];
    NSURL*url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.Dict[@"image"]]];
    [image sd_setImageWithURL:url];
    
    UILabel*name=(UILabel*)[self.view viewWithTag:22];
    name.text=self.Dict[@"name"];
    
    [self initDPMeterView];
    
    UILabel *subcountLabel = (UILabel*)[self.view viewWithTag:33];
    subcountLabel.text=[NSString stringWithFormat:@"已有%@人订阅",self.Dict[@"subcount"]];
    
//    UILabel*date=(UILabel*)[self.view viewWithTag:44];
//    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
//    [dateformat setDateFormat:@"yyyy-MM-dd"];
//    date.text=[dateformat stringFromDate:[NSDate new]];
    
    UILabel*description=(UILabel*)[self.view viewWithTag:55];
    description.text=[NSString stringWithFormat:@"    %@",self.Dict[@"description"]];
}
-(void)initDPMeterView{
    DPMeterView *fiveStarsShape = (DPMeterView *)[self.view viewWithTag:233];;
    [fiveStarsShape setMeterType:DPMeterTypeLinearHorizontal];
    [fiveStarsShape setShape:[UIBezierPath stars:5 shapeInFrame:fiveStarsShape.bounds].CGPath];
    [fiveStarsShape setTrackTintColor:[UIColor lightGrayColor]];
    [fiveStarsShape setProgressTintColor:[UIColor orangeColor]];
    float rate = [self.Dict[@"rate"] intValue];
    [fiveStarsShape setProgress:rate/10 animated:YES];
    [self.view addSubview:fiveStarsShape];
}
-(void)initItmes{
    float size = self.view.frame.size.width/3-5;
    itmeButtons=[[NSMutableArray alloc]init];
    for (long i=0; i<3; i++) {
        UIButton *sbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        [sbutton setFrame:CGRectMake(15+size*i, 245, size-15, 25)];
        [sbutton setFont:[UIFont systemFontOfSize:15]];
        if (i==0) {
            [sbutton setTitle:@"6元/月" forState:UIControlStateNormal];
//            [sbutton addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchUpInside];
        }else if (i==1){
            [sbutton setTitle:@"30元/半年" forState:UIControlStateNormal];
//            [sbutton addTarget:self action:@selector(sixButton:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [sbutton setTitle:@"50元/年" forState:UIControlStateNormal];
//            [sbutton addTarget:self action:@selector(TwelveButton:) forControlEvents:UIControlEventTouchUpInside];
        }
        [sbutton setTag:i];
        sbutton.backgroundColor=UIColorFromRGB(0x8487ba);
        [sbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sbutton setBackgroundImage:nil forState:UIControlStateNormal];
        [sbutton addTarget:self action:@selector(oneButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:sbutton];
        [itmeButtons addObject:sbutton];
    }
    jiantou=[[UIImageView alloc]initWithFrame:CGRectMake(0, 273, 15, 15)];
    jiantou.image=[UIImage imageNamed:@"jiantou.jpg"];
    jiantou.hidden=YES;
    [self.view addSubview:jiantou];
    if ([self.item intValue]<3) {
        [self oneButton:itmeButtons[[self.item intValue]]];
    }
}

- (void)oneButton:(id)sender {
//    self.Money=@"1";
    UIButton*button=(UIButton*)sender;
    [self selectButton];
    jiantou.hidden=NO;
    button.backgroundColor=[UIColor whiteColor];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"subyes"] forState:UIControlStateNormal];
    
    [UIView animateWithDuration:.3 animations:^{
        jiantou.frame=CGRectMake(button.frame.origin.x+button.frame.size.width/2-7.5, 273, 15, 15);
    }];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
//    NSDateComponents *comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate new]];
    
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    

    if (button.tag==0) {
        magidKey=@"1";
        [adcomps setMonth:+1];
    }else if (button.tag==1){
        magidKey=@"6";
        [adcomps setMonth:+6];
    }else if (button.tag==2){
        magidKey=@"12";
        [adcomps setYear:+1];
    }
//    [adcomps setYear:0];
//    [adcomps setMonth:-1];
//    [adcomps setDay:0];
    NSDate *toDate = [calendar dateByAddingComponents:adcomps toDate:[NSDate new] options:0];
    
    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"yyyy-MM-dd"];

    UILabel*date=(UILabel*)[self.view viewWithTag:44];
    date.text=[NSString stringWithFormat:@"%@至%@",[dateformat stringFromDate:[NSDate new]],[dateformat stringFromDate:toDate]];
    
    magid=[self.Dict[@"itemid"] objectForKey:magidKey];
}
-(void)selectButton{
    for (UIButton*button in itmeButtons) {
        button.backgroundColor=UIColorFromRGB(0x8487ba);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setBackgroundImage:nil forState:UIControlStateNormal];
    }

}
//确定购买
- (IBAction)definite:(id)sender {
//    if (magid.length<3) {
//        SHOW_ALERT(@"提示", @"请选择购买类型");
//        return;
//    }
//    
//    [self Subscribe:nil];
    
    
    
    if (IFUserLogin) {
            if (magid.length<3) {
                SHOW_ALERT(@"提示", @"请选择购买类型");
                return;
            }
        
            [self Subscribe:nil];
    }
    
    else{
        newOrderBackGround.hidden = NO;
        litleBlackView.hidden = NO;
    }
    
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    //[SVProgressHUD showSuccessWithStatus:@"订单获取完成."];
    [SVProgressHUD dismiss];
    NSArray *myProduct = response.products;
    NSLog(@"response -- %@",response);
    NSLog(@"response.products -- %@",response.products);
    
    
    if(myProduct.count==0 || myProduct==nil){
        SHOW_ALERT(@"错误", @"无法完成购买：杂志信息错误。");
    }else{
        SKPayment *payment = [SKPayment paymentWithProduct:myProduct[0]];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

//bool isFail = NO;

-(void)Subscribe:(id)obj{
//    if (IFUserLogin) {
    
//        UIButton*button=(UIButton*)obj;
//        magid=[NSString stringWithFormat:@"%@",self.Dict[button.tag-1000][@"magid"]];
        //取出杂志信息
        //NSDictionary *magData = nil;
//        for (NSDictionary *m in ArraySubTable) {
//            if([m[@"magid"] intValue] == [magid intValue]){
//                magData = m;
//                break;
//            }
//        }
//        if(magData == nil){
//            //此处需要提示错误信息并return
//            
//        }
//        NSArray *ids = magData[@"itemid"];
//        if([ids count] == 0){
//            SHOW_ALERT(@"提示", @"该杂志暂未上线。");
//            return;
//        }
//        UIView *v = button.superview;
//        SubscriptionCell *cell = nil;
//        for (long i =0; i<10; i++) {
//            if([v isKindOfClass:[SubscriptionCell class]]){
//                cell = (SubscriptionCell *)v;
//                break;
//            }else{
//                v = v.superview;
//            }
//        }
        //SubscriptionCell *cell = (SubscriptionCell *)[button.superview superview];
        NSString *orderTime = @"";
        if([magidKey  isEqualToString: @"1"]){
            orderTime = @"一期";
        }else if([magidKey isEqualToString: @"6"]){
            orderTime = @"半年";
        }else if([magidKey  isEqualToString: @"12"]){
            orderTime = @"一年";
        }
        NSString *alertMessage = [NSString stringWithFormat:@"您选择的是［%@］杂志［%@］刊，是否确认订阅？",self.Dict[@"name"],orderTime];
//        buyCell = cell;
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"确认订阅" message:alertMessage delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag=11;
        [alert show];
        
//    }
//    else{
//        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
//        LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];//判断用户是否登录，在这里去掉这个判断
//        [self.navigationController pushViewController:login animated:YES];
//    }
}
- (BOOL)verifyTransaction:(SKPaymentTransaction*)transaction{
    [SVProgressHUD showWithStatus:@"正在验证订单数据.." maskType:SVProgressHUDMaskTypeGradient];
    NSLog(@"%@",transaction.transactionDate);
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
    if(receiptData == nil) return NO;
    //NSString *test = [NSString stringWithContentsOfURL:receiptURL encoding:NSUTF8StringEncoding error:nil];
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    //NSString *payload = [ NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}",encodeStr];
    NSString *tid = transaction.transactionIdentifier;
    if(tid == nil) tid = @"";
//    NSLog(@"%d",transaction.transactionState);
//    ,@"debug":@"1"
    NSString *openUdid = [OpenUDID_UDID value];
    NSLog(@"openUdid == %@",openUdid);
    
    [[AppAPIClient sharedClient] POST:@"Magazine/Subscribe" parameters:@{@"id":tid,@"data":encodeStr,@"openudid":openUdid} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([responseObject[@"code"] intValue] == 1){
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            SHOW_ALERT(@"订购提示", @"订购成功，感谢您的支持。");
            [SVProgressHUD showSuccessWithStatus:@"订购成功!"];
            [self.navigationController popViewControllerAnimated:YES];
//            [self doneLoadingViewData];
        }else{
            SHOW_ALERT(@"订购提示", @"订购失败，请尝试恢复购买。");
            [SVProgressHUD showErrorWithStatus:@"订购失败，请尝试恢复购买。"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"订购失败!"];
    }];
    //    [[AppAPIClient sharedClient] POST:@"Magazine/Subscribe" parameters:@{@"id":transaction.transactionIdentifier,@"data":encodeStr} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        if([responseObject[@"code"] intValue] == 1){
    //            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    //            SHOW_ALERT(@"订购提示", @"订购成功，感谢您的支持。");
    //            [SVProgressHUD showSuccessWithStatus:@"订购成功!"];
    //        }else{
    //
    //            SHOW_ALERT(@"订购提示", @"订购失败，请尝试恢复购买。");
    //            [SVProgressHUD showErrorWithStatus:@"订购失败，请尝试恢复购买。"];
    //        }
    //
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        [SVProgressHUD showErrorWithStatus:@"订购失败!"];
    //    }];
    return NO;
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions{
    
    for(SKPaymentTransaction *t in transactions){
        switch (t.transactionState) {
            case SKPaymentTransactionStatePurchased:
                [self verifyTransaction:t];
                //                [SVProgressHUD showErrorWithStatus:@"重复购买"];
                [[SKPaymentQueue defaultQueue] finishTransaction:t];
                break;
            case SKPaymentTransactionStateFailed:{
                NSString *reason = @"";
                if(t.error.code == SKErrorPaymentCancelled){
                    [[SKPaymentQueue defaultQueue] finishTransaction:t];
                    reason = @"用户取消交易。";
                }else if(t.error.code == SKErrorPaymentInvalid){
                    [[SKPaymentQueue defaultQueue] finishTransaction:t];
                    reason = @"无效支付数据。";
                }else if(t.error.code == SKErrorPaymentNotAllowed){
                    [[SKPaymentQueue defaultQueue] finishTransaction:t];
                    reason = @"用户不允许购买。";
                }
                reason = [NSString stringWithFormat:@"订单:%@ 失败,%@",t.transactionIdentifier,reason];
                [[SKPaymentQueue defaultQueue] finishTransaction:t];
                [SVProgressHUD dismiss];
                SHOW_ALERT(@"购买失败", reason);
                break;
            }
            case SKPaymentTransactionStateRestored:
                [[SKPaymentQueue defaultQueue] finishTransaction:t];
                break;
            case SKPaymentTransactionStatePurchasing:
                [SVProgressHUD showWithStatus:@"正在准备支付..." maskType:SVProgressHUDMaskTypeGradient];
                break;
            default:
//                NSLog(@"Case Default : %d",t.transactionState);
                break;
        }
    }
}
#pragma mark - alertView
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==11) {
        if (buttonIndex==1) {
            //            [self doneLoadingViewData];
            if([SKPaymentQueue canMakePayments]){
                //继续支付
                NSString *itemID = [self.Dict[@"itemid"] objectForKey:magidKey];
                NSSet *set = [NSSet setWithArray:@[itemID]];
                NSLog(@"");
                SKProductsRequest *request = [[SKProductsRequest alloc]initWithProductIdentifiers:set];
                request.delegate = self;
                [SVProgressHUD showWithStatus:@"正在获取杂志信息..." maskType:SVProgressHUDMaskTypeGradient];
                [request start];
            }else{
                //用户禁止支付购买
                SHOW_ALERT(@"提示",@"无法完成支付：用户禁止应用内付费购买。" );
                
                /*UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"无法完成支付：用户禁止应用内付费购买。" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
                 [alert show];*/
            }
            
            
        }
        
    }else if (alertView.tag==22){
        if (buttonIndex==1) {
            UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
            [self.navigationController pushViewController:login animated:YES];
        }
    }else{
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)goToLogin:(id)sender {
    newOrderBackGround.hidden = YES;
    litleBlackView.hidden = YES;
    
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController*login=[story instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [self.navigationController pushViewController:login animated:YES];

}

- (IBAction)goToBuy:(id)sender {
    newOrderBackGround.hidden = YES;
    litleBlackView.hidden = YES;
    
    if (magid.length<3) {
        SHOW_ALERT(@"提示", @"请选择购买类型");
        return;
    }
    
    [self Subscribe:nil];

}


@end
